import json
import os
import pandas as pd


def main(path, f):
    # path = r'D:\GJ\项目\铜锣山\sn_ip\2025-01-24\HW7.csv'
    # 加载数据
    data = pd.read_csv(path)
    # 查看数据集行数和列数
    rows, columns = data.shape
    # 将transtime列转换为日期时间格式
    data['transtime'] = pd.to_datetime(data['transtime'])
    # 提取小时信息
    data['hour'] = data['transtime'].dt.hour
    # 按小时分组并计算过车流量
    hourly_traffic = data.groupby('hour').size().reset_index(name='过车流量')
    # # 计算过车流量的分位数
    # q25 = hourly_traffic['过车流量'].quantile(0.25)
    # q75 = hourly_traffic['过车流量'].quantile(0.75)
    # # 定义低密度、中密度、高密度的区间范围
    # low_traffic = hourly_traffic[hourly_traffic['过车流量'] < q25]
    # medium_traffic = hourly_traffic[(hourly_traffic['过车流量'] >= q25) & (hourly_traffic['过车流量'] < q75)]
    # high_traffic = hourly_traffic[hourly_traffic['过车流量'] >= q75]
    # # 输出结果
    # print('低密度过车流量区间范围：')
    # print(low_traffic)
    # print('中密度过车流量区间范围：')
    # print(medium_traffic)
    # print('高密度过车流量区间范围：')
    # print(high_traffic)

    # 定义客货车类型
    data['vehicle_type'] = data['feevehicletype'].apply(lambda x: '客车' if x == 1 else '货车')
    # 按小时和车辆类型分组，统计数量
    hourly_vehicle_count = data.groupby(['hour', 'vehicle_type']).size().unstack(fill_value=0)
    # 计算客货车比例
    hourly_vehicle_count['客货比例(客车/货车)'] = hourly_vehicle_count['客车'] / hourly_vehicle_count['货车']
    # 将过车流量合并到结果中
    result = pd.merge(hourly_traffic, hourly_vehicle_count, on='hour')
    # print('每个小时的过车流量和客货车比例：', result)
    # result = result.reset_index()
    day = os.path.dirname(path)[-10:]
    for index, row in result.iterrows():
        ti = day + "-" + str(int(row['hour'])).zfill(2)
        save_data = {ti: {'过车流量': int(row['过车流量']), '客车数量': int(row['客车']), '货车数量': int(row['货车'])}}
        print(save_data)
        save_data_1 = json.dumps(save_data, ensure_ascii=False)
        f.write(save_data_1 + "\n")


json_path = r'D:\GJ\项目\铜锣山\sn_ip\result.json'
ff = open(json_path, 'w', encoding='utf-8')
for root, dirs, files in os.walk(r'D:\GJ\项目\铜锣山\sn_ip'):
    for dir in dirs:
        if dir == '2025-02-06' or dir == '2025-02-07':
            continue
        dir_path = os.path.join(root, dir, 'HW7.csv')
        print(dir_path)
        main(dir_path, ff)